package com.wzy.springcloudhystrix.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("error/percentage")
public class Order错误率熔断Controller {


    @GetMapping("getOrderById/{id}")
    @HystrixCommand(fallbackMethod = "getOrderByIdFallbackMethod",
            commandProperties = {
            //下面三个熔断属性的含义是 1秒内至少请求两次，然后只要失败率是50% 就触发熔断。
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")
            }
    )
    public OrderDto getOrderById(@PathVariable("id") String id) {
        OrderDto iphone12_pro_max = new OrderDto("1", 1000, "iphone12 pro max");
        count.getAndIncrement();
        if (count.get() % 2 ==0){
            return iphone12_pro_max;
        }else {
            throw new RuntimeException("errr");
        }
    }

    public static volatile AtomicInteger count = new AtomicInteger(0);

    /**
     * 兜底方法，可作为降级方法
     * @param id
     * @return
     */
    public OrderDto getOrderByIdFallbackMethod(String id) {
        return new OrderDto("0", 0, "兜底数据");
    }

}
